import { defineStore } from 'pinia'
import { useStorage } from '@vueuse/core'   //在 localStorage 或 sessionStorage 中存储和同步状态
import defaultSettings from  '@/settings'

//导入Element Plus 中英文语言包
import zhCn from "element-plus/es/locale/lang/zh-cn"
import en from "element-plus/es/locale/lang/en"


export const useAppStore = defineStore('app',() => {
    const device = useStorage('device', 'desktop')
    const size = useStorage('size', defaultSettings.size)
    const language = useStorage('language', defaultSettings.language)
    const sidebarStatus = useStorage('sidebarStatus', 'closed')
    const activeTopMenu = useStorage('activeTopMenu', '')
    const searchHistoryMenus = useStorage<Menu[]>('searchMenus', [])

    const sidebar = reactive({
        opened:sidebarStatus.value != 'closed',
        withoutAnimation:false
    })
    const local = computed(() => {
        if(language?.value == 'en'){
            return en
        }else{
            return zhCn
        }
    })

    function closeSideBar(withoutAnimation:boolean){
        sidebar.opened = false
        sidebar.withoutAnimation = withoutAnimation
        sidebarStatus.value = 'closed'
    }

    function openSideBar(withoutAnimation:boolean){
        sidebar.opened = true
        sidebar.withoutAnimation = withoutAnimation
        sidebarStatus.value = 'opened'
    }

    function toggleSidebar(){
        sidebar.opened = !sidebar.opened
        sidebar.withoutAnimation = false
        if(sidebar.opened){
            sidebarStatus.value = 'opened'
        }else{
            sidebarStatus.value = 'closed'
        }
    }

    //混合模式顶部切换
    function changeTopActive(val:string){
        activeTopMenu.value = val
    }

    function toggleDevice(val:string){
        device.value = val
    }

    function addSearchMenus(menu:Menu){
        // 如果searchHistoryMenus的长度大于0，并且里面的每一项的name与参数里的menu.name不相等就push,否则就不push
        if (searchHistoryMenus.value.length === 0 || !searchHistoryMenus.value.some(item => item.title === menu.title)) {
            searchHistoryMenus.value.push({
                title:menu.title,
                path:menu.path
            })
        }
    }

    function deleteSearchMenus(index:number){
        searchHistoryMenus.value.splice(index,1)
    }

    return {
        device,
        size,
        local,
        language,
        sidebar,
        activeTopMenu,
        closeSideBar,
        changeTopActive,
        toggleSidebar,
        toggleDevice,
        openSideBar,
        searchHistoryMenus,
        addSearchMenus,
        deleteSearchMenus
    }
})